//
//  PlanViewController.m
//  Wallets Manager
//
//  Created by Nguyen Chi Cong on 9/13/12.
//  Copyright (c) 2012 BKHN. All rights reserved.
//

#define kRowHeight  60
#import "PlanViewController.h"
#import "folyAppDelegate.h"

@implementation PlanViewController
@synthesize planTableView;
@synthesize popUpView;
@synthesize planArray;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = NSLocalizedString(@"Lập kế hoạch", @"Plan");
        self.tabBarItem.image = [UIImage imageNamed:@"save-01.png"];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //---------------------NSNotification Center ----------------------//
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadPlanTableView:) name:@"reloadPlanTableView" object:nil];
    // Do any additional setup after loading the view from its nib.
}

- (void) viewWillAppear:(BOOL)animated {
    //--------------------Get Plan Not Completed ----------------------//
    folyAppDelegate *delegate = (folyAppDelegate *)[[UIApplication sharedApplication]delegate];
    planArray = [NSMutableArray arrayWithArray:[DataBaseAccess getPlanByStatus:NO andWallet:delegate.currentWallet]];
    
    for (Plan *plan in planArray) {
        if([plan.p_name isEqualToString:@"Chưa có kế hoạch"]){
            [planArray removeObject:plan];
            break;
        }
    }
    
    [planTableView reloadData];
}

- (void)viewDidUnload
{
    [self setPlanTableView:nil];
    [self setPopUpView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - IBAction Delegate
- (IBAction)viewButtonPressed:(id)sender {
    
    [popup dismissModal];
    
    ViewPlanController *viewPlanController = [[ViewPlanController alloc]init];
    viewPlanController.currentPlan = currentPlan;
    [self.navigationController pushViewController:viewPlanController animated:YES];
}

- (IBAction)backButtonPressed:(id)sender
{
    folyAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
    [appDelegate.navigationController popViewControllerAnimated:YES];
}

- (IBAction)addButtonPressed:(id)sender {
    
    AddPlanViewController *addPlanViewController = [[AddPlanViewController alloc]init];
    addPlanViewController.formKind = @"Add Form";
    [self.navigationController pushViewController:addPlanViewController animated:YES];
}

- (IBAction)editButtonPressed:(id)sender {
    
    [popup dismissModal];
    
    AddPlanViewController *addPlanViewController = [[AddPlanViewController alloc]init];
    addPlanViewController.formKind = @"Edit Form";
    addPlanViewController.currentPlan = currentPlan;
    [self.navigationController pushViewController:addPlanViewController animated:YES];
}

- (IBAction)deleteButtonPressed:(id)sender {
    [planArray removeObject:currentPlan];
    folyAppDelegate *delegate = [[UIApplication sharedApplication]delegate];
    [DataBaseAccess movePlan:currentPlan.p_name toPlan:@"Chưa có kế hoạch" andWallet:delegate.currentWallet];
    [popup dismissModal];
    [planTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:currentIndexPath] withRowAnimation:UITableViewRowAnimationFade];
    
}

#pragma mark - Table View Delegate

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  [planArray count];
}

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return  1;
}
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0,320,40)];
    headerView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"sub_navbar_bg.png"]];
    
    UILabel *sectionTitleLabel = [[UILabel alloc]initWithFrame:CGRectMake(5, -5, 100, 30)];
    sectionTitleLabel.text = @"Running";
    sectionTitleLabel.textColor = [UIColor whiteColor];
    sectionTitleLabel.font = [UIFont systemFontOfSize:14];
    sectionTitleLabel.backgroundColor = [UIColor clearColor];
    [headerView addSubview:sectionTitleLabel];
    
    return headerView;
}

-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CustomPlanCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellInditifier"] ;
    Plan * tempPlan = [planArray objectAtIndex:indexPath.row];
    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPress:)];
    
    if( cell == nil) {
        
        //UIViewController *viewForCell = [[UIViewController alloc]initWithNibName:@"CustomPlanCell" bundle:nil] ;
        NSArray* nibViews =  [[NSBundle mainBundle] loadNibNamed:@"CustomPlanCell" owner:self options:nil];
        
        cell = (CustomPlanCell *)[nibViews objectAtIndex:0];
        //cell = (CustomPlanCell *) viewForCell.view;
        //[cell addGestureRecognizer:longTap];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    cell.planNameLabel.text = tempPlan.p_name;
    cell.imageView.image = [UIImage imageNamed:tempPlan.p_image];
    cell.startAmountLabel.text = [NSString stringWithFormat:@"%d",[tempPlan.p_startamount intValue]];
    
    //Set Width for StartAmount to Fit StartAmount TextField Background
    NSString *amountString =[NSString stringWithFormat:@"%f",[tempPlan.p_amount doubleValue]];
    CGSize textLabelSize = [amountString sizeWithFont:[UIFont systemFontOfSize:12]];
    CGRect startAmountFrame = cell.startAmountLabel.frame;
    cell.startAmountLabel.frame = CGRectMake(320-12-textLabelSize.width +20,startAmountFrame.origin.y, textLabelSize.width-20, startAmountFrame.size.height);
    
    cell.destinationAmountLabel.text = [NSString stringWithFormat:@"%d",[tempPlan.p_amount intValue]];

    return cell;
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    currentIndexPath = indexPath;
    currentPlan = [planArray objectAtIndex:indexPath.row];
    if (indexPath == nil)
        NSLog(@"long press on table view but not on a row");
    else
        NSLog(@"long press on table view at row %d", indexPath.row);
    
    CGRect currentRowFrame = CGRectMake(0, 0, 320, kRowHeight);
    currentRowFrame.origin.y = kRowHeight * (indexPath.row +1) +30;
    
    
    
    if (popup == nil) {
        popup = [[SNPopupView alloc] initWithContentView:popUpView contentSize:CGSizeMake(170, 60)];
		
        [popup presentModalAtPoint:CGPointMake(currentRowFrame.origin.x, currentRowFrame.origin.y) inView:self.view animated:YES];
		
		[popup addTarget:self action:@selector(didTouchPopupView:)];
		//[popup release];
		[popup setDelegate:self];
	}
	else if (NO) {
		[popup dismiss:YES];
		popup = nil;
	}

}
#pragma mark - NSNotification Center Delegate

- (void) reloadPlanTableView : (NSNotification *) notification {
    folyAppDelegate *delegate = (folyAppDelegate *)[[UIApplication sharedApplication]delegate];
    planArray = [NSMutableArray arrayWithArray:[DataBaseAccess getPlanByStatus:NO andWallet:delegate.currentWallet]];
    [planArray removeObjectAtIndex:0];
    [planTableView reloadData];
    
}

#pragma mark - Gesture Delegate
-(void) handleLongPress: (UIGestureRecognizer *)longPress {
    
    CGPoint p = [longPress locationInView:planTableView];
    
    NSIndexPath *indexPath = [planTableView indexPathForRowAtPoint:p];
    currentIndexPath = indexPath;
    currentPlan = [planArray objectAtIndex:indexPath.row];
    if (indexPath == nil)
        NSLog(@"long press on table view but not on a row");
    else
        NSLog(@"long press on table view at row %d", indexPath.row);
    
    CGRect currentRowFrame = CGRectMake(0, 0, 320, kRowHeight);
    currentRowFrame.origin.y = kRowHeight * (indexPath.row +1) +30;
    
    
    
    if (popup == nil) {
        popup = [[SNPopupView alloc] initWithContentView:popUpView contentSize:CGSizeMake(170, 60)];
		
        [popup presentModalAtPoint:CGPointMake(currentRowFrame.origin.x, currentRowFrame.origin.y) inView:self.view animated:YES];
		
		[popup addTarget:self action:@selector(didTouchPopupView:)];
		//[popup release];
		[popup setDelegate:self];
	}
	else if (NO) {
		[popup dismiss:YES];
		popup = nil;
	}
    
    
}

#pragma mark - PopUp Delegate

- (void)didTouchPopupView:(SNPopupView*)sender {
    //	DNSLogMethod
    //	DNSLog(@"%@", sender);
}



- (void)didDismissModal:(SNPopupView*)popupview {
	//DNSLogMethod
	if (popupview == popup) {
		popup = nil;
	}
}

@end
